package com.jy.api.controller.clerk;

import com.jy.api.dao.EmployeeDao;
import com.jy.api.dao.MemberAccountDao;
import com.jy.api.dao.OrderDao;
import com.jy.api.domain.Employee;
import com.jy.api.domain.Order;
import com.jy.api.service.RewardService;
import com.jy.api.util.Contens;
import com.jy.api.util.MyDateUtils;
import com.jy.api.vo.clerk.CommissionVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by lihu on 2017/8/25.
 */
@Slf4j
@RestController
@RequestMapping(value = "v1/clerk", produces = "application/json;charset=utf-8")
public class CommissionController {


    @Autowired
    OrderDao orderDao;

    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    MemberAccountDao memberAccountDao;
    @Autowired
    private RewardService rewardService;


    /**
     * 获取员工当月业绩信息
     *
     * @param storeId
     * @param principal
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/commission")
    public ResponseEntity getCommission(@RequestParam(value = "storeId") String storeId,
                                        @RequestParam(value = "page", defaultValue = "0") int page,
                                        Principal principal) {
        try {
            if (page < 0) {
                page = 0;
            }
            Employee employee = employeeDao.findByStoreIdAndUsernameAndEnabled(storeId,
                    principal.getName(), true);
            if (employee == null) {
                return new ResponseEntity("查询失败！员工信息不存在！", HttpStatus.BAD_REQUEST);
            }
            ZoneId america = ZoneId.of("Asia/Shanghai");
            LocalDate today = LocalDate.now();
            LocalDate firstDayOfThisMonth = today.with(TemporalAdjusters.firstDayOfMonth());
            ZonedDateTime startZdt = firstDayOfThisMonth.atStartOfDay(america);
            Date start = Date.from(startZdt.toInstant());
            Map<String, Object> map = orderDao.getCommissionTotal(storeId, principal.getName(),
                    start, new Date());
            Date lastMonthStart = Date.from(firstDayOfThisMonth.minusMonths(1).
                    atStartOfDay(america).toInstant());
            Map<String, Object> map1 = orderDao.getCommissionTotal(storeId, principal.getName(),
                    lastMonthStart, start);
            Map<String, Object> map2 = orderDao.getCommissionTotal(storeId, principal.getName(), MyDateUtils.getEarliest(new Date()), MyDateUtils.getLastest(new Date()));

            Object sameMonth = memberAccountDao.getReferralUserMemberCount(storeId, principal.getName(), start, new Date());
            Object lastMonth = memberAccountDao.getReferralUserMemberCount(storeId, principal.getName(), lastMonthStart, start);

            //获取上月总提成
            Double commissionTotal1 = Double.parseDouble(map1.get("amount").toString());
            Double commissionTotal = Double.parseDouble(map.get("amount").toString());
            Double last = Double.parseDouble(map2.get("amount").toString());
            Integer orderSize = Integer.parseInt(map.get("total").toString());
            CommissionVo commissionVo = new CommissionVo(commissionTotal, orderSize);
            commissionVo.setLastMonth(commissionTotal1);
            commissionVo.setLastDayAmount(last);
            commissionVo.setSameMonthMemberCount(Integer.parseInt(sameMonth.toString()));
            commissionVo.setLastMonthMemberCount(Integer.parseInt(lastMonth.toString()));
            List<Order> orders = orderDao.getOrders(storeId, principal.getName(),
                    start, new Date(), Contens.PAGE_SIZE * page, Contens.PAGE_SIZE);
            for (Order order : orders) {
                CommissionVo.Order orderVo = new CommissionVo.Order();
                BeanUtils.copyProperties(order, orderVo);
                commissionVo.getOrders().add(orderVo);
            }
            return new ResponseEntity(commissionVo, HttpStatus.OK);
        } catch (Exception ex) {
            log.error("getCommission is error==> storeId:{},principal:{}", storeId, principal, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("get-reward")
    public ResponseEntity getEmpReward(@RequestParam(name = "empId", required = false) String empId, @RequestParam(name = "from", required = false) String from, @RequestParam(name = "storeId", required = false) String storeId, @RequestParam(name = "year", required = false) Integer year, @RequestParam(name = "month", required = false) Integer month, @RequestParam(name = "source", required = false) String source, @RequestParam(name = "type", required = false) String type, @RequestParam(value = "judge", required = false) String judge) {
        try {
            return ResponseEntity.ok(rewardService.getEmpRewards(empId, from, source, type, storeId, year, month, judge));
        } catch (Exception ex) {
            log.error("get-reward is error==> empId:{}", empId, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("get-empRe")
    public ResponseEntity getEmpRe(@RequestParam("storeId") String storeId) {
        return ResponseEntity.ok(rewardService.getEmp(storeId));
    }


}
